%% RCT2Scale empirical analysis
% Replicates Figure 10 right column

% Set max iteration number and tolerance
max_iter = 5000;
tol = 0.0001;

% Random seed
seed = 101;
rng(seed)

%% Case 1: N=66, J=2, grouping 1
N = 66;
J = 2;
meta_nu_list = 0:0.4:20;

% Extract study estimates and ses
sheet1 = 'Estimates';
sheet2 = 'SE';
estimates1 = xlsread('../Data/RCT2Scale_data.xlsx', sheet1, 'A2:C67'); 
se1 = xlsread('../Data/RCT2Scale_data.xlsx', sheet2, 'A2:C67');   

% Randomly assign baseline and validation studies
[hat_theta_1, hat_vartheta_1, rep_base_se2_1, rep_val_se2_1] = random_assignment(estimates1, se1, seed);

% Estimate nu
EB_est_nu_1 = MLE_nu(hat_theta_1, rep_base_se2_1, 0, max_iter, tol);

% Calculate and plot ecf as a function of nu
empirical_cov_list_1 = ecf_over_nu(hat_theta_1, rep_base_se2_1, hat_vartheta_1, rep_val_se2_1, meta_nu_list);
xtick = 0:2:20;
ytick = 0.3:0.1:1;
cov_plot_1 = plot_cov_over_nu(empirical_cov_list_1, meta_nu_list, EB_est_nu_1, xtick, ytick);
saveas(cov_plot_1, '../Results/nu_plot_N_66_J_2_g1.png');

%% Case 2: N=66, J=2, grouping 2
N = 66;
J = 2;
meta_nu_list = 0:0.4:20;

% Extract study estimates and ses
sheet1 = 'Estimates';
sheet2 = 'SE';
estimates2 = xlsread('../Data/RCT2Scale_data2.xlsx', sheet1, 'A2:C67'); 
se2 = xlsread('../Data/RCT2Scale_data2.xlsx', sheet2, 'A2:C67');   

% Randomly assign baseline and validation studies
[hat_theta_2, hat_vartheta_2, rep_base_se2_2, rep_val_se2_2] = random_assignment(estimates2, se2, seed);

% Estimate nu
EB_est_nu_2 = MLE_nu(hat_theta_2, rep_base_se2_2, 0, max_iter, tol);

% Calculate and plot ecf as a function of nu
empirical_cov_list_2 = ecf_over_nu(hat_theta_2, rep_base_se2_2, hat_vartheta_2, rep_val_se2_2, meta_nu_list);
xtick = 0:2:20;
ytick = 0.3:0.1:1;
cov_plot_2 = plot_cov_over_nu(empirical_cov_list_2, meta_nu_list, EB_est_nu_2, xtick, ytick);
saveas(cov_plot_2, '../Results/nu_plot_N_66_J_2_g2.png');
